const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs-extra');
const path = require('path');

router.post('/login', (req, res) => {
  if (req.body.password === global.admin_password) {
    req.session.authenticated = true;
    res.json({ success: true });
  } else {
    res.status(401).json({ error: 'Invalid password' });
  }
});

const authMiddleware = (req, res, next) => {
  if (req.session.authenticated) {
    next();
  } else {
    res.status(401).json({ error: 'Authentication required' });
  }
};
module.exports = authMiddleware;

router.get('/', (req, res) => {
  res.sendFile(path.join(global.INIT_DIR, './public/admin/admin.html')); 
});

// 普通上传配置
const upload = multer({ dest: global.UPLOAD_DIR });
router.post('/upload', authMiddleware, upload.array('files'), (req, res) => {
  const files = req.files;
  files.forEach(file => {
    const originalName = file.originalname; // 获取原始文件名
    const newFilePath = path.join(global.UPLOAD_DIR, originalName);
    fs.renameSync(file.path, newFilePath); // 重命名文件
  });
  res.json({ success: true });
});

// 分块上传配置
const chunkUpload = multer({ dest: global.UPLOAD_TMP_DIR }).single('file');
router.post('/upload-chunk', authMiddleware, chunkUpload, (req, res) => {
  const { filename, chunkNumber } = req.body;
  const tempDir = path.join(global.UPLOAD_TMP_DIR, filename);
  fs.ensureDirSync(tempDir);
  fs.renameSync(req.file.path, path.join(tempDir, chunkNumber));
  res.json({ success: true });
});

// 合并分块
router.post('/merge-chunks', authMiddleware, async (req, res) => {
  const { filename, totalChunks } = req.body;
  const tempDir = path.join(global.UPLOAD_TMP_DIR, filename);
  const finalPath = path.join(global.UPLOAD_DIR, filename);
  
  const chunks = await fs.readdir(tempDir);
  if (chunks.length !== parseInt(totalChunks)) {
    return res.status(400).send('Chunk count mismatch');
  }

  const writeStream = fs.createWriteStream(finalPath);
  for (let i = 0; i < totalChunks; i++) {
    const chunkPath = path.join(tempDir, i.toString());
    await fs.appendFile(finalPath, await fs.readFile(chunkPath));
    await fs.unlink(chunkPath);
  }
  await fs.remove(tempDir);
  res.json({ success: true });
});

module.exports = router;